// ComputerPlayer.cpp
//
// Created By: Jeremy Butler
// Created On: 24-Mar-2011

#include "ComputerPlayer.h"
#include "ChessController.h"
#include <algorithm>
using namespace std;

ComputerPlayer::ComputerPlayer() : ChessPlayer(), state(0), controller(NULL){
  return;
}

ComputerPlayer::ComputerPlayer(Color _color, ChessController * _controller) :
    ChessPlayer(_color), controller(_controller),
    state(0){
  return;
}

ComputerPlayer::ComputerPlayer(const ComputerPlayer & other) :
    ChessPlayer(other), state(other.state), controller(other.controller){
  return;
}

ComputerPlayer::~ComputerPlayer(){
  return;
}

void ComputerPlayer::on_TimerEvent(){
  if(state == 0)
    SelectPiece();
  else
    MovePiece();
}

void ComputerPlayer::SelectPiece(){
  const set<Piece *> & pieces = controller->model->GetPieces(GetColor());
  cout << "Size of pieces: ";
  cout << pieces.size();
  cout << endl;
  Piece * piece;
  set<Location> moves;
  while(moves.empty()){
    int random = rand() % pieces.size();
    cout << random;
    cout << endl;
    set<Piece *>::iterator it = pieces.begin();
    for(int i = 0; i < random; i++){
      it++;
    }
    piece = *it;
    Location location(controller->model->GetPieceLocation(piece));
    int row = location.GetY();
    int col = location.GetX();
    moves = (*it)->GetValidMoves(controller->model->GetBoard(),row,col);

    if(!moves.empty()){
      controller->UnhighlightAll();
      controller->HighlightValidMoves(moves,row,col);
      controller->model->SetSelectedSpace(row,col);
    }
  }
  state = 1;
}

void ComputerPlayer::MovePiece(){
  Location selectedLocation(controller->model->GetSelectedSpace());
  int row = selectedLocation.GetY();
  int col = selectedLocation.GetX();
  set<Location> moves = controller->model->GetValidMoves(row,col);
  int random = rand() % moves.size();
  set<Location>::iterator it = moves.begin();
  for(int i = 0; i < random; i++){
    it++;
  }
  int toRow = it->GetY();
  int toCol = it->GetX();
  const Move * lastMove = controller->model->MovePiece(toRow, toCol);
  controller->UnhighlightAll();

  controller->view->ClearPiece(row, col);
  controller->view->PlacePiece(toRow, toCol,
	    controller->GetImageName(*((*(controller->model))(toRow,toCol))));
  controller->view->WriteMessageArea("\n" + lastMove->ToString() + "\n\n");
  controller->UpdateGameState();

  state = 0;
}

void ComputerPlayer::Reset(){
  state = 0;
}
